<?php 
namespace app\app\model;
use think\Model;
use think\Db;

/**
* 口袋模型
*/
class Pocket extends Model
{
	public $user_id;

	function __construct($data)
	{
		$this->user_id = $data;
	}

	public function savePocket($data=[],$id)
	{
		if ( $data && !empty($data) ){
			$p_id = array();
			$list = array();
			//总价
			$total_price = 0;
			foreach($data as $k => $v){
				$goods = Db::name('goods')->where('id','eq',$v->id)->find();
				$pocket = array(
					'user_id'  => $this->user_id,
					'store_id' => $id,
					'goods_id' => $v->id,
					'num'      => $v->number,
					'price'    => $goods['price']
				);
				$pid = Db::name('pocket')->insertGetId($pocket);
				$p_id[] = $pid;
				//生成订单信息
				//价格
				$price = $goods['price']*($v->number);

				$total_price = $total_price + $price;
				$arr = array(
					'name'   => $goods['name'],
					'image'  => config('IMG_HEAD').$goods['image'],
					'number' => $v->number,
					'price'  => $price
				);
				$list[] = $arr;
			}
			//查询配送费==
			$store = Db::name('store')->where('id','eq',$id)->find();
			$total_price = $total_price + $store['distribute'];
			//是否有优惠
			return ['total_price'=>$total_price,'p_id'=>$p_id];
		} else {
			return false;
		}
	}

	public function calculate($data)
	{
		//查询商户
		$store  = Db::name('store')->where('id','eq',$data['store_id'])->find();
		//查询口袋
		$price = $store['distribute'];
		$pid  = $data['pocket'];
		for($i=0;$i<count($pid);$i++){
			$pocket = $this->where('id','eq',$pid[$i])->find();
			$price = $price + $pocket['num']*$pocket['price'];
		}
		//查询是否有优惠
		return $price;
	}

}